import { reactive } from "vue";
import { io } from "socket.io-client";
import { host_custom } from "@/host.js";

export const state = reactive({
    connected: false,
    fooEvents: [],
    barEvents: []
});

let socket = null;
let listenersInitialized = false;

export const useSocket = () => {
    if (!socket) {
        socket = io(host_custom)
    }
    if (!listenersInitialized) {
        listenersInitialized = true;
        socket.on("connect", () => {
            state.connected = true;
        });
        socket.on("disconnect", () => {
            state.connected = false;
        });
        socket.on("foo", (...args) => {
            state.fooEvents.push(args);
        });
        socket.on("bar", (...args) => {
            state.barEvents.push(args);
        });
    }
    return socket;
}

export const disconnectSocket = () => {
    if (socket) {
        socket.disconnect();
        socket = null;
        listenersInitialized = false;
    }
}